package services

import (
	"time"

	"gopkg.in/mgo.v2/bson"

	"zaiqiuchang.com/server/models"
)

// 业务对象结构，通过json tag指定对外输出形式
type User struct {
	ID         string     `json:"id"`
	Username   string     `json:"username"`
	Password   string     `json:"-"`
	Salt       string     `json:"-"`
	Nickname   string     `json:"nickname"`
	Gender     string     `json:"gender"`
	Mobile     string     `json:"mobile,omitempty"`
	CreateTime *time.Time `json:"create_time"`
	UpdateTime *time.Time `json:"update_time,omitempty"`
}

// 将model对象转换成业务对象
func NewUserFromModel(mu *models.User) (u *User) {
	return &User{
		ID:         mu.ID.Hex(),
		Username:   mu.Username,
		Password:   mu.Password,
		Salt:       mu.Salt,
		Nickname:   mu.Nickname,
		Gender:     mu.Gender,
		Mobile:     mu.Mobile,
		CreateTime: timePointerZeroNil(mu.CreateTime),
		UpdateTime: timePointerZeroNil(mu.UpdateTime),
	}
}

// 创建用户
func CreateUser(u *User) (err error, cu *User) {
	uc, err := models.NewUserColl()
	if err != nil {
		return NewError(ErrCodeSystem, err.Error()), nil
	}

	salt := randString(8, []rune{})
	password := md5StringSalt(u.Password, salt)
	err = uc.Insert(models.User{
		Username:   u.Username,
		Password:   password,
		Salt:       salt,
		Nickname:   u.Nickname,
		Gender:     u.Gender,
		Mobile:     u.Mobile,
		CreateTime: time.Now(),
	})
	if err != nil {
		return NewError(ErrCodeSystem, err.Error()), nil
	}

	return GetUserByUsername(u.Username)
}

// 编辑用户资料
func UpdateUser(id string, u *User) (err error, uu *User) {
	// ...
}

// 查询用户信息
func GetUser(id string) (err error, u *User) {
	// ...
}

// 更具用户名查询用户信息
func GetUserByUsername(username string) (err error, u *User) {
	// ...
}

// 验证用户名密码
func VerifyUserPassword(username string, password string) (err error, u *User) {
	// ...
}
